package org.apache.log4j;

import java.io.File;
import java.io.InputStream;
import java.net.URL;

import org.apache.log4j.spi.LoggerRepository;

import com.z1.core.PathUtil;
import com.z1.core.exception.Z1Exception;

public class CustomLoggerFactory {
	
	public static void loadLogger() {
		final String log4jConfigPath = "/log4j.properties";
		URL log4jConfigUrl = CustomLoggerFactory.class.getResource(log4jConfigPath);
		if (null != log4jConfigUrl) {
			System.out.println("log4j：" + log4jConfigUrl.getPath());
			InputStream inputStream = CustomLoggerFactory.class.getResourceAsStream(log4jConfigPath);
			PropertyConfigurator.configure(inputStream);
		}
		else {
			File log4jFile =  new File(PathUtil.getConfDir(), "log4j.properties");
			System.out.println("log4j：" + log4jFile.getAbsolutePath());
			if (null != log4jFile && log4jFile.exists() && log4jFile.isFile()) {
				PropertyConfigurator.configure(log4jFile.getAbsolutePath());
			}
		}
    }
	
	public static void addLogger(String name) {
		if (null == name) {
			throw new Z1Exception("日志名称为空.");
		}
		Logger rootLogger = Logger.getRootLogger();
		LoggerRepository hierarchy = LogManager.getLoggerRepository();
		if (null != hierarchy.exists(name)) {
			return;
		}
		Logger logger = hierarchy.getLogger(name, new DefaultCategoryFactory());
		logger.setLevel(rootLogger.getLevel());
		
		//Appender
		File logFile = new File(PathUtil.getAppDir(), "logs/" + name + ".log");
		if (logFile.exists() && logFile.isFile()) { }
		else {
			logFile.getParentFile().mkdirs();
			try { logFile.createNewFile(); }
			catch (Throwable e) { }
		}
		
		try {
			RollingFileAppender appender = new RollingFileAppender(
				new PatternLayout("%d{yyyy-MM-dd HH:mm:ss,SSS} %p %t %m%n"), 
				logFile.getAbsolutePath()
			);
			
			appender.setName(name);
			appender.setMaxFileSize("10MB");
			appender.setMaxBackupIndex(1);
			
			logger.addAppender(appender);
		}
		catch (Throwable e) {
			throw new Z1Exception(e);
		}
	}
	
}
